#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import re
import pycurl
import StringIO

import FileHostProtoType


class dfitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class depositfiles(FileHostProtoType.FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "DepositFiles" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.logtype = 'poster'
        self._cookieCurl = '%s_%s.cookie' % (self._user, self.hostname)
        self._cookieCurl = os.path.join(os.path.dirname(__file__), self._cookieCurl)
            
    def login(self):
        if self.islogin:
            return True
        #build opener
        self.generateOpener()
        if self.restore_cookiejar():
            return True
            
        self.fherr.write('login to DepositFiles %s/%s...'%(self._user,'*'*len(self._pwd)))
        loginData = {'login' : self._user, \
                'password' : self._pwd,
                'go' : '1'}
        response = self.loginFileHost("http://depositfiles.com/login.php?return=%2F", loginData)
        if "recaptcha" in response:
            self.fherr.write("User %s Failed to Login DepositFiles." % self._user)
            self.fherr.write("It seems your ip is blocked. Use Web browser to try to relogin.")
            return False
        index = self.post_request("http://depositfiles.com/")
        # user info can be found in cookie
        if self._user.lower() not in index.lower():
            self.fherr.write("User %s Failed to Login DepositFiles." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        self._cj.save(self._cookieCurl, ignore_discard=True)
        return True

    def restore_cookiejar(self):
        '''
        load cookie file, then access website to verify if cookie is avaiable
        '''
        if os.path.isfile(self._cookieCurl):
            self.fherr.write('Restore Local Cookie.')
            try:
                self._cj.load(self._cookieCurl, ignore_discard=True)
            except:
                self.fherr.write('Failed to Restore Local CookieJar.')
            #access website to conferm cookie is avaiable
            return self.check_cookie()
        return False
        
    def check_cookie(self):
        self.fherr.write('Checking Cookie...')
        response = self.post_request("http://depositfiles.com/")
        if response and self._user in response:
            self.fherr.write("User %s Status : Logined." % self._user)
            self.islogin = True             
            return True
        self.fherr.write("[%s]User %s Status : not Logined." % (time.ctime(), self._user))
        #self.fherr.write(response)
        return False  
        
    def find(self, filenames = [], filelist = None):
        found = []
        if filelist == None:
            return found      
        filelistlower = [fl.name.lower() for fl in filelist]
        todel = []
        for fl in filenames:
            try:
                index = filelistlower.index(os.path.basename(fl).lower())
                found.append(filelist[index])
                todel.append(fl)
            except:
                continue
        for d in todel:
            filenames.remove(d)
        found.sort()
        return found
        
    def getFileList(self):
        return []
    
    def get_upload_key(self, content, key, index, sed='"'):
        lines = content.split('\n')
        for line in lines:
            if key in line:
                tokens = line.split(sed)
                value = tokens[index]
                return value
        return ''
    
    def upload_web(self, file, progressLog=None, other_args=None):
        #indexpage        
        get_upload_info_url = 'http://depositfiles.com/'
        get_upload_info_page = self.post_request(get_upload_info_url).encode('utf8','ignore')
        
        upload_link = self.get_upload_key(get_upload_info_page, 'id="upload_form"', -4)
        max_file_size = self.get_upload_key(get_upload_info_page, 'name="MAX_FILE_SIZE"', -2)
        upload_identifier = self.get_upload_key(get_upload_info_page, 'name="UPLOAD_IDENTIFIER"', -2)
        
        time_ticket = self.get_timeticket(10)
        server_links_tokens = upload_link.split('=')
        upload_link = server_links_tokens[0] + '=' + time_ticket + server_links_tokens[1]
        #print upload_link
        #print max_file_size, upload_identifier
        
        data = {"MAX_FILE_SIZE":max_file_size,
                "UPLOAD_IDENTIFIER":upload_identifier,
                "go":"1",
                "agree":"1",
                "padding":"",
                "files":open(file, 'rb')}
        self.fherr.write("Uploading...%s" % file)
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_request(upload_link, data, cb=callback, setfilename=self.rename_func(file))
        #result
        #print result
        if not 'upload_done()' in result:
            self.fherr.write(result)
            self.fherr.write("orz:" + upload_link)
            self.fherr.write("Failed to upload %s" % file)
            #time.sleep(300)
            return

        link = self.get_upload_key(result, 'ud_download_url', -2, sed="'")
        link += "/" + self.rename_func(file)
        item = dfitem(os.path.basename(file), 'file', '', link, self.rename_func(file))
        self.newupload.append(item)
        self.fhout.write(item.format()) 
        #self.fherr.write("yeh:" + upload_link)
        return item